<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.mobile"
        clearable
        class="filter-item"
        :placeholder="$t('user_user.placeholder.filter_mobile')"
      />
      <el-select
        v-model="listQuery.userLevel"
        clearable
        placeholder="用户等级"
        class="filter-item"
        @change="handleFilter"
      >
        <el-option
          v-for="(item, index) in levelDic"
          :key="index"
          :label="item"
          :value="index"
        />
      </el-select>
      <el-button type="primary" icon="el-icon-search" @click="handleFilter">{{
        $t("app.button.search")
      }}</el-button>
      <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      <!-- <el-button
          :loading="downloadLoading"
          class="filter-item"
          type="primary"
          icon="el-icon-download"
          @click="handleDownload"
          >{{ $t("app.button.download") }}</el-button
        > -->
    </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      :element-loading-text="$t('app.message.list_loading')"
      :header-cell-style="{
        background: 'rgba(239, 241, 244, 0.2)',
        color: '#333333',
      }"
      border
      fit
    >
      <el-table-column
        align="center"
        width="100px"
        :label="$t('user_user.table.id')"
        prop="id"
        sortable
      />

      <el-table-column
        align="center"
        :label="$t('user_user.table.nickname')"
        prop="nickname"
      />

      <el-table-column
        align="center"
        :label="$t('user_user.table.mobile')"
        prop="mobile"
      />

      <el-table-column
        align="center"
        :label="$t('user_user.table.gender')"
        prop="gender"
      >
        <template slot-scope="scope">
          <el-tag
            :type="
              scope.row.gender === 1
                ? 'primary'
                : scope.row.gender === 2
                ? 'success'
                : 'info'
            "
            >{{ genderDic[scope.row.gender] }}</el-tag
          >
        </template>
      </el-table-column>
      <!-- 
      <el-table-column
        align="center"
        :label="$t('user_user.table.birthday')"
        prop="birthday"
      /> -->

      <el-table-column
        align="center"
        :label="$t('user_user.table.user_level')"
        prop="userLevel"
      >
        <template slot-scope="scope">
          <el-tag
            :type="
              scope.row.userLevel === 0
                ? 'info'
                : scope.row.userLevel === 1
                ? 'warning'
                : 'danger'
            "
            >{{ levelDic[scope.row.userLevel] }}</el-tag
          >
        </template>
      </el-table-column>

      <!-- <el-table-column
        align="center"
        :label="$t('user_user.table.status')"
        prop="status"
      >
        <template slot-scope="scope">
          <el-tag>{{ statusDic[scope.row.status] }}</el-tag>
        </template>
      </el-table-column> -->
      <el-table-column
        align="center"
        :label="$t('user_user.table.actions')"
        width="100"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button type="text" @click="handleDetail(scope.row)"
            >编辑</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <!-- 用户编辑对话框 -->
    <el-dialog
      width="60%"
      :visible.sync="userDialogVisible"
      :title="$t('user_user.dialog.edit')"
    >
      <el-form
        ref="userDetail"
        :model="userDetail"
        status-icon
        label-width="100px"
      >
        <el-form-item
          :label="$t('user_user.form.username') + '：'"
          prop="username"
        >
          <el-input v-model="userDetail.username" :disabled="true" />
        </el-form-item>
        <el-form-item
          :label="$t('user_user.form.nickname') + '：'"
          prop="nickname"
        >
          <el-input v-model="userDetail.nickname" />
        </el-form-item>
        <el-form-item :label="$t('user_user.form.mobile') + '：'" prop="mobile">
          <el-input v-model="userDetail.mobile" />
        </el-form-item>
        <el-form-item :label="$t('user_user.form.gender') + '：'" prop="gender">
          <el-select
            v-model="userDetail.gender"
            :placeholder="$t('user_user.placeholder.gender')"
            ><el-option
              v-for="(item, index) in genderDic"
              :key="index"
              :label="item"
              :value="index"
          /></el-select>
        </el-form-item>
        <el-form-item
          :label="$t('user_user.form.user_level') + '：'"
          prop="userLevel"
        >
          <el-select
            v-model="userDetail.userLevel"
            :placeholder="$t('user_user.placeholder.user_level')"
            ><el-option
              v-for="(item, index) in levelDic"
              :key="index"
              :label="item"
              :value="index"
          /></el-select>
        </el-form-item>
        <!-- <el-form-item :label="$t('user_user.form.status') + '：'" prop="status">
          <el-select
            v-model="userDetail.status"
            :placeholder="$t('user_user.placeholder.status')"
            ><el-option
              v-for="(item, index) in statusDic"
              :key="index"
              :label="item"
              :value="index"
          /></el-select>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="userDialogVisible = false">{{
          $t("app.button.cancel")
        }}</el-button>
        <el-button type="primary" @click="handleUserUpdate">{{
          $t("app.button.confirm")
        }}</el-button>
      </div>
    </el-dialog>

    <!-- <div>
      待实现的功能
      <ul>
        <li>统计每个用户下单次数和金额,自动分配不同的用户等级</li>
      </ul>
    </div> -->
  </div>
</template>

<script>
import { fetchList, userDetail, updateUser } from "@/api/user";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination

export default {
  name: "User",
  components: { Pagination },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        username: undefined,
        mobile: undefined,
        userId: undefined,
        userLevel: undefined,
        sort: "add_time",
        order: "desc",
      },
      downloadLoading: false,
      genderDic: ["未知", "男", "女"],
      levelDic: ["普通用户", "VIP用户", "高级VIP用户"],
      statusDic: ["可用", "禁用", "注销"],
      userDialogVisible: false,
      userDetail: {},
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.listLoading = true;
      if (this.listQuery.userId) {
        userDetail(this.listQuery.userId)
          .then((response) => {
            this.list = [];
            if (response.data.data) {
              this.list.push(response.data.data);
              this.total = 1;
              this.listLoading = false;
            } else {
              this.list = [];
              this.total = 0;
              this.listLoading = false;
            }
          })
          .catch(() => {
            this.list = [];
            this.total = 0;
            this.listLoading = false;
          });
      } else {
        fetchList(this.listQuery)
          .then((response) => {
            this.list = response.data.data.list;
            this.total = response.data.data.total;
            this.listLoading = false;
          })
          .catch(() => {
            this.list = [];
            this.total = 0;
            this.listLoading = false;
          });
      }
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleDownload() {
      this.downloadLoading = true;
      import("@/vendor/Export2Excel").then((excel) => {
        const tHeader = ["用户名", "手机号码", "性别", "生日", "状态"];
        const filterVal = [
          "username",
          "mobile",
          "gender",
          "birthday",
          "status",
        ];
        excel.export_json_to_excel2(tHeader, this.list, filterVal, "用户信息");
        this.downloadLoading = false;
      });
    },
    handleDetail(row) {
      this.userDetail = { ...row };
      this.userDialogVisible = true;
    },
    handleUserUpdate() {
      updateUser(this.userDetail)
        .then((response) => {
          this.userDialogVisible = false;
          this.$message.success({
            title: "成功",
            message: "更新用户成功",
          });
        })
        .catch((response) => {
          this.$message.error({
            title: "失败",
            message: response.data.errmsg,
          });
        });
    },
    resetQuery() {
      this.listQuery = {
        page: 1,
        limit: 20,
        username: undefined,
        mobile: undefined,
        userId: undefined,
        userLevel: undefined,
        sort: "add_time",
        order: "desc",
      };
      this.getList();
    },
  },
};
</script>
